<template>
  <div>
    <div class="gva-search-box">
      <!-- 搜索框内容 -->
    </div>
    <div class="gva-table-box">
      <div class="gva-btn-list">
        <el-button type="primary" icon="plus" @click="openDialog">
          新增
        </el-button>
      </div>
      <!-- 组件 -->
      <el-table
        :data="tableData"
        @sort-change="sortChange"
        @selection-change="handleSelectionChange"
      >

        <el-table-column
            align="left"
            label="服务能力名称"
            min-width="150"
            prop="Name"
            sortable="custom"
        />
        <el-table-column
            align="left"
            label="状态"
            min-width="150"
            prop="Status"
            sortable="custom"
        >
          <template #default="{ row }">
            {{ formatStatus(row.Status) }}
          </template>
        </el-table-column>

        <el-table-column
            align="left"
            label="使用方式"
            min-width="150"
            prop="UseType"
            sortable="custom"
        >
          <template #default="{ row }">
            {{ formatUseType(row.UseType) }}
          </template>
        </el-table-column>




      <el-table-column align="left" label="开始时间" min-width="200" prop="CreatedAt" sortable>
          <template #default="scope">
            {{ formatDate(scope.row.AllowTime) }}
          </template>
        </el-table-column>

        <el-table-column align="left" label="过期时间" min-width="200" prop="CreatedAt" sortable>
          <template #default="scope">
            {{ formatDate(scope.row.ExpiredTime) }}
          </template>
        </el-table-column>

<!--        <el-table-column align="left" fixed="right" label="操作" width="200">-->
<!--          <template #default="scope">-->
<!--            &lt;!&ndash;            <el-button type="primary" link @click="opendrawerVisible(scope.row)">&ndash;&gt;-->
<!--            &lt;!&ndash;              编辑&ndash;&gt;-->
<!--            &lt;!&ndash;            </el-button>&ndash;&gt;-->
<!--            <el-button type="primary" link @click="deleteApiFunc(scope.row)">-->
<!--              删除-->
<!--            </el-button>-->
<!--          </template>-->
<!--        </el-table-column>-->
      </el-table>
      <div class="gva-pagination">
        <el-pagination
          :current-page="page"
          :page-size="pageSize"
          :page-sizes="[10, 30, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>
    <el-drawer
      v-model="drawerVisible"
      title="新增节点"
      direction="rtl"
      :size="drawerSize"
      @close="resetForm"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">

        <el-form-item label="服务能力Id" prop="serviceItemId">
          <el-select v-model="form.serviceItemId" placeholder="请选择服务能力">
            <el-option
                v-for="item in capabilityList"
                :key="item.ServiceItemId"
                :label="item.ServiceItemName"
                :value="item.ServiceItemId"
            />
          </el-select>
        </el-form-item>


        <el-form-item label="使用方式" prop="UseType">
          <el-select v-model="form.UseType" placeholder="请选择使用方式">
            <el-option label="次数" :value="1"></el-option>
            <el-option label="流量" :value="2"></el-option>
            <el-option label="期限" :value="3"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="开始时间" prop="AllowTime">
          <el-date-picker
              v-model="form.AllowTime"
              type="datetime"
              placeholder="请选择开始时间"
              :format="'YYYY-MM-DD HH:mm:ss'"
              :value-format="'YYYY-MM-DD HH:mm:ss'"
          />
        </el-form-item>

        <el-form-item label="过期时间" prop="ExpiredTime">
          <el-date-picker
              v-model="form.ExpiredTime"
              type="datetime"
              placeholder="请选择过期时间"
              :format="'YYYY-MM-DD HH:mm:ss'"
              :value-format="'YYYY-MM-DD HH:mm:ss'"
          />
        </el-form-item>
        <el-button @click="drawerVisible = false"> 取消 </el-button>
        <el-button type="primary" @click="submitForm"> 确定 </el-button>
      </el-form>
    </el-drawer>
  </div>
</template>


<script setup>
import { ref, onMounted } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import {useRoute} from "vue-router";
import {
  getListAppAllowServiceItem,
  RegisAppAllowService

} from "@/api/application";
import {
  getCapabilityList,

} from "@/api/service";
const route = useRoute()
const page = ref(1);
const total = ref(0);
const pageSize = ref(10);
const tableData = ref([]);
const capabilityList = ref([]);
const serviceData = ref([]);
const AppId =ref('')
const drawerVisible = ref(false);
const drawerSize = ref("40%");
const formRef = ref(null);
const form = ref({
  ServiceID: "",
  Name: "",
  ServiceConfig: "",
  AllowTime: "",
  ExpiredTime: "",
  UseType: null,
  serviceItemId: "",
});

const rules = {
  ServiceID: [{ required: true, message: "请输入ID", trigger: "blur" }],
  ServiceConfig: [
    { required: true, message: "请输入服务配置", trigger: "blur" },
  ],
  AllowTime: [{ required: true, message: "请选择开始时间", trigger: "change" }],
  ExpiredTime: [{ required: true, message: "请选择过期时间", trigger: "change" }],
};

const fetchCapabilityList = async () => {
  try {
    const ServiceId = route.query.ServiceId || '';
    const response = await getCapabilityList(page.value, pageSize.value, ServiceId);
    console.log("Fetched capability list:", response.data.list); // 打印数据以检查
    if (response.code === 0) {
      capabilityList.value = response.data.list; // 确保数据正确赋值
    } else {
      ElMessage.error(response.msg || "获取服务能力列表失败");
    }
  } catch (error) {
    console.error("API Error:", error);
    ElMessage.error("获取服务能力列表失败");
  }
};


const formatStatus = (Status) => {
  switch (Status) {
    case 1: return '过期'; // Expired
    case 2: return '禁用'; // Disabled
    case 3: return '正常'; // Normal
    case 4: return '暂停'; // Suspended
    default: return '未知'; // Unknown
  }
}

const formatUseType = (UseType) => {
  switch (UseType) {
    case 1: return '次数'; // Times
    case 2: return '流量'; // Traffic
    case 3: return '期限'; // Duration
    default: return '未知'; // Unknown
  }
}


const opendrawerVisible = (row) => {
  form.value = {
    ServiceID: row.ServiceID,
    Name: row.Name,
    ServiceConfig: row.ServiceConfig,
    ExpiredTime: row.ExpiredTime,
    AllowTime: row.AllowTime,// Convert to Date object for date-picker
  };
  drawerVisible.value = true;
};
const change = (value) => {
  const isTrue = serviceData.value.find((list) => list.ServiceId === value);

  if (isTrue) {
    form.value.ServiceName = isTrue.ServiceName;
  } else {
    form.value.ServiceName = "";
  }
  console.log(form.value.ServiceName);
};

const getTableData = async () => {
  try {
    AppId.value = route.query.AppId || ''
    const response = await getListAppAllowServiceItem(page.value, pageSize.value,AppId.value);
    if (response.code === 0) {
      tableData.value = response.data.list.map((item) => ({
        ...item,
        AllowTime: new Date(item.AllowTime), // Convert to Date object for table display
      }));
      total.value = response.data.total;
    } else {
      ElMessage.error(response.msg || "获取数据失败");
    }
  } catch (error) {
    console.error("API Error:", error);
    ElMessage.error("获取数据失败");
  }
};

onMounted(() => {
  getTableData();
  fetchCapabilityList(); // Fetch capability list
});

const openDialog = () => {
  form.value = {
    ServiceID: "",
    ServiceConfig: "",
    AllowTime: new Date(),
    ExpiredTime: "",
    UseType: null,
    serviceItemId: "", // 确保清空或设置默认值
  };
  drawerVisible.value = true;
  fetchCapabilityList(); // 确保数据是最新的
};


const resetForm = () => {
  formRef.value.resetFields();
};

const formatDate = (date) => {
  if (date) {
    const d = new Date(date);
    const year = d.getFullYear();
    const month = String(d.getMonth() + 1).padStart(2, "0");
    const day = String(d.getDate()).padStart(2, "0");
    const hours = String(d.getHours()).padStart(2, "0");
    const minutes = String(d.getMinutes()).padStart(2, "0");
    const seconds = String(d.getSeconds()).padStart(2, "0");
    return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}Z`; // 转换为 ISO 8601 格式
  }
  return "";
};



const submitForm = async () => {
  try {
    await formRef.value.validate();
    const payload = {
      Name: form.value.Name,
      serviceItemId: form.value.serviceItemId, // 使用服务项ID进行提交
      AllowTime: formatDate(form.value.AllowTime),
      ExpiredTime: formatDate(form.value.ExpiredTime),
      UseType: parseInt(form.value.UseType), // 确保 UseType 传递为整数
      AppId: route.query.AppId
    };
    await RegisAppAllowService(payload);
    ElMessage.success("添加成功");
    drawerVisible.value = false;
    getTableData();
  } catch (error) {
    console.error("Form Submit Error:", error);
    ElMessage.error("添加失败");
  }
};



const deleteApiFunc = (row) => {
  ElMessageBox.confirm("确认删除此配置？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    try {
      await deleteServiceConfig({ id: row.ID });
      ElMessage.success("删除成功");
      getTableData();
    } catch (error) {
      console.error("Delete Error:", error);
      ElMessage.error("删除失败");
    }
  });
};

const handleCurrentChange = (newPage) => {
  page.value = newPage;
  getTableData();
};

const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  getTableData();
};

const sortChange = () => {
  // 处理排序逻辑
};
</script>


<style scoped>
.gva-search-box {
  margin-bottom: 20px;
}

.gva-table-box {
  margin-bottom: 20px;
}

.gva-btn-list {
  margin-bottom: 20px;
}

.gva-pagination {
  margin-top: 20px;
}
</style>
